__imghelp = {
    /** 压缩图片
     * @param {Object} file 上传对象files[0]
     * @param {Object} options 压缩设置对象
     * @param {Function} callback 回调函数
     * @result {Object} 返回blob文件对象
     * @example 
     * {float} options.size 期望大小（M）
     * {float 0.1 - 1} options.scale 按比例缩放
     * {boolen} options.Orientation 修正方向
     * {boolen} options.Square 正方形裁剪
     * {boolen} options.Rectangle 长方形裁剪(9:6)
     * {boolen} options.Rectangle2 长方形裁剪(3:1)
     * */
    compressImg: (file, options) => {
        var self = this;
        var Orientation = null;
        if (options.Orientation) {
            EXIF.getData(file, function () {
                Orientation = EXIF.getTag(this, 'Orientation');
            });
        }
        return new Promise(r => {
            var imgname = file.name;
            var imgtype = (imgname.substring(imgname.lastIndexOf('.') + 1)).toLowerCase();
            if (imgtype == 'jpg' || imgtype == 'jpeg') {
                imgtype = 'image/jpeg';
            } else {
                imgtype = 'image/png';
            }
            // 用FileReader读取文件
            var reader = new FileReader();
            // 将图片读取为base64
            reader.readAsDataURL(file);
            reader.onload = function (evt) {
                var base64 = evt.target.result;
                // 创建图片对象
                var img = new Image();
                // 用图片对象加载读入的base64
                img.src = base64;
                img.onload = function () {
                    let that = this,
                        canvas = document.createElement('canvas'),
                        ctx = canvas.getContext('2d');

                    let _width = that.width, _height = that.height;

                    //如果图片太大，先缩小
                    while (_width > 1000 || _height > 1000) {
                        _width *= 0.9;
                        _height *= 0.9;
                    }

                    canvas.setAttribute('width', _width);
                    canvas.setAttribute('height', _height);
                    // 将图片画入canvas
                    //画之前先看看是否要旋转
                    if (Orientation && Orientation != 1) {
                        switch (Orientation) {
                            case 6: // 旋转90度
                                canvas.width = _height;
                                canvas.height = _width;
                                ctx.rotate(Math.PI / 2);
                                // (0,-_height) 从旋转原理图那里获得的起始点
                                ctx.drawImage(this, 0, -_height, _width, _height);
                                break;
                            case 3: // 旋转180度
                                ctx.rotate(Math.PI);
                                ctx.drawImage(this, -_width, -_height, _width, _height);
                                break;
                            case 8: // 旋转-90度
                                canvas.width = _height;
                                canvas.height = _width;
                                ctx.rotate(3 * Math.PI / 2);
                                ctx.drawImage(this, -_width, 0, _width, _height);
                                break;
                        }
                    } else {
                        ctx.drawImage(that, 0, 0, _width, _height);
                    }

                    //裁剪图片
                    if (options.Square) {
                        //将图片裁剪成正方形
                        let x, y, w, h;
                        if (_height > _width) {//长图
                            x = 0;
                            y = (_height - _width) / 2;
                            w = _width;
                            h = _width;
                        }
                        else {//宽图
                            x = (_width - _height) / 2;;
                            y = 0;
                            w = _height;
                            h = _height;

                        }
                        var imgdata = ctx.getImageData(x, y, w, h);
                        canvas.width = w;
                        canvas.height = h;
                        ctx.putImageData(imgdata, 0, 0);
                    }
                    else if (options.Rectangle) {
                        //将图片裁剪成长方形(9:6)
                        let x, y, w, h;
                        if (_height / 6 > _width / 9) {//长图
                            w = _width;
                            h = _width * 6 / 9;
                            x = 0;
                            y = (_height - h) / 2;
                        }
                        else {//宽图
                            w = _height * 9 / 6;
                            h = _height;
                            x = (_width - w) / 2;;
                            y = 0;

                        }
                        
                        var imgdata = ctx.getImageData(x, y, w, h);
                        canvas.width = w;
                        canvas.height = h;
                        ctx.putImageData(imgdata, 0, 0);
                    } else if (options.Rectangle2) {
                        //将图片裁剪成长方形(3:1)
                        let x, y, w, h;
                        if (_height / 1 > _width / 3) {//长图
                            w = _width;
                            h = _width * 1 / 3;
                            x = 0;
                            y = (_height - h) / 2;
                        }
                        else {//宽图
                            w = _height * 3 / 1;
                            h = _height;
                            x = (_width - w) / 2;;
                            y = 0;

                        }
                        
                        var imgdata = ctx.getImageData(x, y, w, h);
                        canvas.width = w;
                        canvas.height = h;
                        ctx.putImageData(imgdata, 0, 0);
                    }

                    let output = false;

                    if (options.size) {
                        // 压缩到指定体积以下（M）
                        var scale = 0.9;
                        (function f(scale) {
                            if (base64.length / 1024 / 1024 > options.size && scale > 0) {
                                output = true;
                                base64 = canvas.toDataURL(imgtype, scale);
                                scale = scale - 0.1;
                                f(scale);
                            }
                        })(scale);
                    } else if (options.scale) {
                        // 按比率压缩
                        output = true;
                        base64 = canvas.toDataURL(imgtype, options.scale);
                    }
                    if (!output) {
                        //没有压缩则执行1:1输出(输出旋转或裁剪结果)
                        base64 = canvas.toDataURL(imgtype, 1);
                    }
                    r(__imghelp.convertBase64ToBlob(base64));
                };
            };
        });
    },

    //将blob转换为file
    blobToFile: (theBlob, fileName) => {
        theBlob.lastModifiedDate = new Date();
        theBlob.name = fileName;
        return theBlob;
    },
    /** 将base64转换为文件对象
     *  @param {String} base64 base64字符串
     * */
    convertBase64ToBlob: (base64) => {
        var base64Arr = base64.split(',');
        var imgtype = '';
        var base64String = '';
        if (base64Arr.length > 1) {
            //如果是图片base64，去掉头信息
            base64String = base64Arr[1];
            imgtype = base64Arr[0].substring(base64Arr[0].indexOf(':') + 1, base64Arr[0].indexOf(';'));
        }
        // 将base64解码
        var bytes = atob(base64String);
        //var bytes = base64;
        var bytesCode = new ArrayBuffer(bytes.length);
        // 转换为类型化数组
        var byteArray = new Uint8Array(bytesCode);

        // 将base64转换为ascii码
        for (var i = 0; i < bytes.length; i++) {
            byteArray[i] = bytes.charCodeAt(i);
        }

        // 生成Blob对象（文件对象）
        return new Blob([bytesCode], {
            type: imgtype
        });
    },
    compressImgOrientation: (file, options) => {
        options.Orientation = 1;
        return __imghelp.compressImg(file, options);
    },
};

const ci = __imghelp;